package xc.utils;

import java.sql.Connection;
import java.sql.SQLException;

public class TransactionManager {
    private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();


    public static Connection getCurrentConnection() throws SQLException {
        Connection conn = threadLocal.get();
        if (conn == null || conn.isClosed()) {
            conn = JdbcUtils.getConnection();
            threadLocal.set(conn);
        }
        return conn;
    }

    public static void beginTransaction() throws SQLException {
        Connection conn = getCurrentConnection();
        conn.setAutoCommit(false);
    }

    public static void commit() throws SQLException {
        Connection conn = getCurrentConnection();
        if (conn != null) {
            conn.commit();
        }
    }

    public static void rollback() throws SQLException {
        Connection conn = getCurrentConnection();
        if (conn != null) {
            conn.rollback();
        }
    }

    public static void release() throws SQLException {
        Connection conn = threadLocal.get();
        if (conn != null) {
            try {
                conn.setAutoCommit(true);
                JdbcUtils.returnConnection(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                threadLocal.remove();
            }
        }
    }
}
